/*
 *    Copyright (c) 2018-2025, proj All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the proj developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: proj
 */

package com.ykht.proj.coupon.controller.c;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ykht.proj.common.core.constant.CacheConstants;
import com.ykht.proj.common.core.util.R;
import com.ykht.proj.common.security.annotation.Inner;
import com.ykht.proj.common.security.util.SecurityUtils;
import com.ykht.proj.coupon.entity.CnPerson;
import com.ykht.proj.coupon.service.CnPersonService;
import com.ykht.proj.coupon.utils.AES;
import com.ykht.proj.coupon.vo.BindMiniVo;
import com.ykht.proj.coupon.vo.ObtainWechatUserInformationVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;


/**
 * 消费者用户表
 *
 * @author proj code generator
 * @date 2020-11-16 17:00:21
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("c/person")
@Api(value = "person", tags = "c端消费者用户相关")
@Slf4j
@RefreshScope
public class PersonController {

	private final CnPersonService cnPersonService;
	private final RedisTemplate redisTemplate;

	/**
	 * 微信小程序
	 */
//	@Autowired
//	private final WxMaService wxMaService;
	@Inner
	@GetMapping("social/{inStr}")
	public R getUserInfo(@PathVariable String inStr) {
		return R.ok(cnPersonService.getUserInfo(inStr));
	}


//	@ApiOperation(value = "获取用户信息")
//	@PostMapping("/getInfo")
//	public R getInfo(@RequestBody ObtainWechatUserInformationVo bindMiniVo) {
//		log.info("->获取用户信息");
//		// 用户信息校验
//		if (!wxMaService.getUserService().checkUserInfo(bindMiniVo.getSessionKey(), bindMiniVo.getRawData(), bindMiniVo.getSignature())) {
//			throw new RuntimeException("用户信息校验失败");
//		}
//		return R.ok(wxMaService.getUserService().getUserInfo(bindMiniVo.getSessionKey(), bindMiniVo.getEncryptedData(), bindMiniVo.getIv()));
//	}


	@ApiOperation(value = "小程序绑定手机号")
	@PostMapping("/bindMini")
	public R bindMini(@RequestBody BindMiniVo bindMiniVo) {

		log.info("->小程序绑定手机号");
		CnPerson cnPerson = cnPersonService.getById(SecurityUtils.getPersonId());
		String sessionKey = null;
		try {
			sessionKey = String.valueOf(redisTemplate.opsForValue().get(CacheConstants.USER_SEEESINKEY_BY_OPENID + cnPerson.getOpenId()));
			log.info("->openid:{}，得到缓存中的sessionKey：{}", cnPerson.getOpenId(), sessionKey);
			redisTemplate.delete(CacheConstants.USER_SEEESINKEY_BY_OPENID + cnPerson.getOpenId());

			String result = AES.wxDecrypt(bindMiniVo.getEncrypted(), sessionKey, bindMiniVo.getIv());
//			String  result = SecureUtil.aes(sessionKey.getBytes()).setIv(bindMiniVo.getIv().getBytes()).decryptStr(bindMiniVo.getEncrypted());
			log.info("->aes解密,result:{}", result);
			JSONObject jsonObject = JSONObject.parseObject(result);
			String phoneNumber = jsonObject.getString("phoneNumber");

			if (cnPersonService.getOne(Wrappers.lambdaQuery(CnPerson.class).eq(CnPerson::getPhone, phoneNumber)) != null)
				return R.failed("此手机号已经绑定过");

			cnPerson.setPhone(phoneNumber);
			cnPersonService.updateById(cnPerson);
			return R.ok(phoneNumber);
		} catch (Exception e) {
			e.printStackTrace();
			redisTemplate.opsForValue().set(CacheConstants.USER_SEEESINKEY_BY_OPENID + cnPerson.getOpenId(), sessionKey);
			return R.failed();
		}
	}

	@ApiOperation(value = "小程序绑定头像昵称")
	@PostMapping("/bindNickname")
	public R bindNickname(@RequestBody CnPerson cnPerson) {
		log.info("->小程序绑定手机号");
		cnPerson.setId(SecurityUtils.getPersonId());
		cnPerson.setAuthBaseStatus(0);//0授权1未授权
		return R.ok(cnPersonService.updateById(cnPerson));
	}

	@ApiOperation(value = "通过id查询")
	@GetMapping("/{id}")
	public R<CnPerson> getById(@PathVariable("id") Long id) {
		return R.ok(cnPersonService.getById(id));
	}
	@ApiOperation(value = "通过ids查询")
	@GetMapping("/byIds")
	public R getByIds(@RequestParam("ids") String ids) {
		String[] id= ids.split(",");
		return R.ok(cnPersonService.list(Wrappers.lambdaQuery(CnPerson.class).in(CnPerson::getId,id)));
	}
	@ApiOperation(value = "通过ids查询")
	@GetMapping("/byIdsFromIn")
	@Inner(false)
	public R byIdsFromIn(@RequestParam("ids") String ids) {
		String[] id= ids.split(",");
		return R.ok(cnPersonService.list(Wrappers.lambdaQuery(CnPerson.class).in(CnPerson::getId,id)));
	}



	@ApiOperation(value = "通过id查询")
	@GetMapping("getByPhone/{phone}")
	public R<CnPerson> getById(@PathVariable("phone") String phone) {
		return R.ok(cnPersonService.getOne(Wrappers.lambdaQuery(CnPerson.class).eq(CnPerson::getPhone, phone)));
	}
}
